jQuery(document).ready(function() {

    // jQuery Tabs script
    jQuery('html,body').scrollTop(0);
    jQuery('#slider').tabs({fxFade: true, fxSpeed: 'fast'});
    //jQuery('#slider').tabs( "select", 2 ); // activate second tab 
    jQuery('#slider').css('display', 'block');

    //ADD Gallery SCRIPT
    // Override default error message
    jQuery.validator.messages.required = "";

    jQuery.validator.addMethod(
            "regex",
            function(value, element, regexp) {
                var check = false;
                return this.optional(element) || regexp.test(value);
            },
            "Please check your input."
            );


    // Override generation of error label
    jQuery("#addgallery_form").validate({
        rules: {
            galleryname: {
                required: true,
                /*regex: /^\s*[A-Za-z0-9 -_\s]+s*$/*/
                regex: /^\w+$/
            }
        },
        submitHandler: function(form) {

            if (jQuery('input[name="galleryname"]').val() == "") {
                alert('Enter gallery name');
                return false;
            }

            if (jQuery('#post_type').val() == 0) {
                alert('Please choose gallery type!');
                return false;
            }


            jQuery('#add_gallery').attr('disabled', 'disabled');
            var form = jQuery("#addgallery_form");
            var form_data = form.serialize();

            jQuery('.ajax-loading').css('visibility', 'visible');

            jQuery.ajax({
                url: form.attr('action'),
                dataType: 'json',
                type: "POST",
                data: form_data,
                success: function(data, textStatus, xhr) {
                    jQuery('.ajax-loading').css('visibility', 'hidden');

                    if (data.action) {
                        jQuery('.loader').html(data.msg);
                        // REDIRECT
                        function promo_show() {
                            window.location.href = base_url + 'gallery/view_new?post_type=' + post_type;
                        }
                        window.setTimeout(function() {
                            promo_show();
                        }, 1001);
                    } else {
                        alert(data.msg);
                        jQuery('#add_gallery').removeAttr('disabled');
                    }

                },
                error: function(xhr, textStatus, errorThrown) {
                    jQuery('.ajax-loading').css('visibility', 'hidden');
                    alert('Error ocured...\n Server not found.');
                    jQuery('#add_gallery').removeAttr('disabled');

                }
            });

            return false;

        }


    });

    jQuery('#add_gallery').removeAttr('disabled');


    //jQuery Upload Files script
    var folder = 'tempatt/';

    var uploader = new plupload.Uploader({
        runtimes: 'flash',
        flash_swf_url: base_url + 'assets/js/libs/plupload/plupload.flash.swf',
        browse_button: 'plupload-browse-button ',
        container: 'plupload-upload-ui',
        url: base_url + 'assets/js/libs/plupload/upload.php',
        multipart: false,
        multipart_params: {'datafield': folder},
        unique_names: false,
        /*resize : { quality : 80},  */
        // Specify what files to browse for
        filters: [
            {title: "Image files", extensions: "jpg,jpeg,gif,png,JPG,JPEG,GIF,PNG"}
        ]

    });

    uploader.settings.multipart_params.datafield = folder;

    uploader.init();

    uploader.bind('FilesAdded', function(up, files) {
        // loop through the files array
        for (var i in files) {
            document.getElementById('uploadQueue').innerHTML += '<div id="' + files[i].id + '">[<a href="javascript:">remove</a>] ' + files[i].name + ' (' + plupload.formatSize(files[i].size) + ') <b></b></div>';
        }
        //console.log(uploader.settings.multipart_params.datafield)  
    });

    uploader.bind('UploadProgress', function(up, file) {
        document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
    });

    uploader.bind('Error', function(up, args) {
        alert(args.code + ': ' + args.message);
    });

    document.getElementById('plupload_btn').onclick = function() {

        if (jQuery('#uploadQueue').children().length == 0) {
            alert('Please select files to upload')
            return false;
        }

        if (jQuery('#galleryselect').val() == 0) {
            alert('Please choose gallery')
            return false;
        }

        jQuery('#uploadimage .ajax-loading').css('visibility', 'visible');
        jQuery('#uploadimage .message p').html('Please wait while images are being uploaded');
        jQuery('#uploadimage .message').show();

        uploader.start();
    };

    uploader.bind('BeforeUpload', function(up, file) {

        galleryselect = jQuery("#galleryselect").val();

        path = galleryselect.split("<--delimiter!-->");

        up.settings.url = base_url + 'assets/js/libs/plupload/upload.php' + "?gellery_path=" + "pro-gallery/" + path[1] + '/';
    });


    uploader.bind('FileUploaded', function(up, file, info) {

        /*console.log(up);
         console.log(file);
         console.log(info);
         console.log(info.response);   //"{"jsonrpc" : "2.0", "result" : null, "id" : "id", "datafield" : "accommodationsbanner_01_15.jpg"}"                         
         */

        var obj = jQuery.parseJSON(info.response);
        //console.log(obj.datafield);                             

        jQuery('#uploadimage_form').append('<input type="hidden" name="pictures[]" value="' + obj.datafield + '" />');
        jQuery('#uploadimage_form').append('<input type="hidden" name="pic_titles[]" value="' + file.name + '" />');

        if ((uploader.total.uploaded) == uploader.files.length) {
            //window.location = 'uploaded.php?file=' + encodeURIComponent(File.name);
            //console.log("uploaded complete:"+File.name);
            //alert("Upload complete")
            jQuery('#uploadimage .message p').html('Creating thumbnails :: Please wait');
            jQuery('#uploadimage_form').submit();

        }
        ;

    });

    jQuery('#uploadQueue a').live('click', function() {

        jQuery(this).parent().fadeOut('slow').remove();
    })


    //jQuery Upload Videos script
    $('#yt-check').live('click', function() {

        var file = $('#yt-link').val();

        if (file == '') {
            alert("Molio unesite link.");
            return;
        }

        $('#video-preview').html('<iframe width="270" height="170" src="http://www.youtube.com/embed/' + file + '" frameborder="0" allowfullscreen></iframe>');

    });



    jQuery('input[name="uploadvideo"]').live('click', function() {

        if (jQuery('#galleryselect2').val() != 0) {
            jQuery('#uploadvideo_form').submit();
            jQuery('#uploadvideo .ajax-loading').css('visibility', 'visible');
            jQuery('#uploadvideo .message p').html('Please wait while creating video link');
            jQuery('#uploadvideo .message').show();
        } else {
            alert('Please choose gallery')
            return false;
        }

    });


});